import SoftKey6A from './SoftKey6A'
import router from '@/router'
import {Message} from 'element-ui'

/**
 * @param {*} callback 
 * @returns 
 */
export function myonLoad(callback) {
  try {
    let s_pnp = new SoftKey6A();
    s_pnp.Socket_UK.onopen = function () {
      // bConnect = 1; //代表已经连接，用于判断是否安装了客户端服务
    };

    //在使用事件插拨时，注意，一定不要关掉Sockey，否则无法监测事件插拨
    s_pnp.Socket_UK.onmessage = function got_packet(Msg) {
      let PnpData = JSON.parse(Msg.data);
      if (PnpData.type == "PnpEvent") {
        //如果是插拨事件处理消息
        if (PnpData.IsIn) {
          // alert("UKEY已被插入，被插入的锁的路径是：" + PnpData.DevicePath);
        } else {
          Message({ message: "UKEY已被拨出", type: 'error' })
          // alert("UKEY已被拨出，被拨出的锁的路径是：" + PnpData.DevicePath);
        }
        callback ? callback() : ''
      }
    };

    s_pnp.Socket_UK.onclose = function () {};

    router.beforeEach((to, from, next) => {
      s_pnp.Socket_UK.close()
      next()
    })
  } catch (e) {
    alert(e.name + ": " + e.message);
    return false;
  }
}

function getDevics(mSoftKey) {
  let isReturn = false, num = 0, devicPaths = [];
  return new Promise(async (resolve, reject) => {
    while(!isReturn) {
      let path = await mSoftKey.FindPort(num); //'查找是否存在多把加密锁
      if (mSoftKey.GetLastError() != 0) {
        isReturn = true
        resolve(devicPaths)
      } else {
        devicPaths.push(path)
        num = num + 1
      }
    }
  })
}

async function getInfo(news, devicPath) {
  let addr, username, password;
  //储存在加密锁的用户名
  {
    addr = 0; //用户名储存在0开如的地址中，之前要用我们的设用户名及密码工具设置
    //先从地址0读取字符串的长度,使用默认的读密码"FFFFFFFF","FFFFFFFF"
    let OutLenBuf = await news.YRead(
      addr,
      1,
      "ffffffff",
      "ffffffff",
      devicPath
    );
    let nlen = OutLenBuf[0];
    if (news.GetLastError() != 0) {
      window.alert(
        "读取用户名长度时错误。错误码：" + news.GetLastError().toString()
      );
      return false;
    }
    //再从地址1读取相应的长度的字符串，,使用默认的读密码"FFFFFFFF","FFFFFFFF"
    username = await news.YReadString(
      addr + 1,
      nlen,
      "ffffffff",
      "ffffffff",
      devicPath
    );
    if (news.GetLastError() != 0) {
      window.alert(
        "读取用户名时错误。错误码：" + news.GetLastError().toString()
      );
      return false;
    }
  }
  //储存在加密锁的用户密码，与上面的区别在于地址不一样，
  {
    addr = 20; //用户密码储存在0开如的地址中，之前要用我们的设用户名及密码工具设置
    //先从地址0读取字符串的长度,使用默认的读密码"FFFFFFFF","FFFFFFFF"
    let OutLenBuf = await news.YRead(
      addr,
      1,
      "ffffffff",
      "ffffffff",
      devicPath
    );
    let nlen = OutLenBuf[0];
    if (news.GetLastError() != 0) {
      window.alert(
        "读取用户密码长度时错误。错误码：" +
          news.GetLastError().toString()
      );
      return;
    }
    //再从地址1读取相应的长度的字符串，,使用默认的读密码"FFFFFFFF","FFFFFFFF"
    password = await news.YReadString(
      addr + 1,
      nlen,
      "ffffffff",
      "ffffffff",
      devicPath
    );
    if (news.GetLastError() != 0) {
      window.alert(
        "读取用户密码时错误。错误码：" + news.GetLastError().toString()
      );
      return false;
    }
  }
  let chip_id = await news.GetChipID(devicPath) // 芯片id
  let ukey_id = await news.GetID(devicPath) // 锁id
  let version = await news.NT_GetIDVersion(devicPath) // 锁的版本
  let expand_version = await news.NT_GetVersionEx(devicPath) // 拓展版本
  // let secret_key_one = await news.GetChipID(devicPath) // 密钥1
  // let secret_key_two = await news.GetChipID(devicPath) // 密钥2
  // let start_url = await news.GetChipID(devicPath) // 启动URI
  return {
    username,
    password,
    chip_id,
    ukey_id,
    expand_version,
    version,
  }
}

export async function getInfoLists() {
  let mSoftKey3A = new SoftKey6A(); //注意，由于USB的操作是异步的，所以所有函数的调用前必须加await !!!!!!!!!
  let devics = await getDevics(mSoftKey3A)
  return devics.reduce(async(pre, cur) => {
    let info = await getInfo(mSoftKey3A, cur)
    pre = await pre
    pre.push(info)
    return pre
  }, Promise.resolve([]))
}

export default {
  myonLoad,
  getInfoLists,
}